﻿@model SpaceNeedle.City6473.WebSite.Models.RequestItemsModel
@using SpaceNeedle.City6473.Web.Data.Models
@using Newtonsoft.Json

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    
    var staticContent = ViewBag.StaticContent as WebSiteContent;
    ViewBag.Title = staticContent.RequestItems.PageTitle;
    
    string jsonStatus = JsonConvert.SerializeObject(ViewBag.ListStatus);
    string jsonRequestItems = JsonConvert.SerializeObject(Model.RequestItems.Select(x =>
                new
                {
                    Id = x.Id,
                    Address = x.Address,
                    RequestTitle = x.Request.Title,
                    RequestDescription = x.Request.Description,
                    Photo = x.Photo,
                    Geoposition = x.Geoposition,
                    UserName = x.User.Name,
                    CreationDate = x.CreationDate,
                    Status = x.Status,
                    StatusInfo = x.StatusInfo,
                    Description = x.Description
                })); 
}

<script charset="UTF-8" type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&mkt=pt-br">
</script>

<style>
#currentdetail .modal-body {
	max-height: 1024px;
}

#currentdetail {
	width: 1024px; 
	margin: -46px 0 0 -512px; 
}
    .map {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        border: #555555 2px solid;
        z-index:99;
        display:none;
    }

    #closeMap
    {
        color:white;
        font-size:24px;
        position:fixed;
        right:30px;
        top:10px;
        cursor:pointer;
        z-index:9999;
        font-weight:bold;
        display:none;
    }
</style>

<div id="map" class="map"></div>
<div id="closeMap" onclick="HideMap();">X</div>

<script>
    @*//Developing with the 7.0 Map Control http://msdn.microsoft.com/en-us/library/gg427606.aspx*@
    var map;
    var requestItems = JSON.parse('@Html.Raw(jsonRequestItems)');

    function ShowMap()
    {
        //var pin = new Microsoft.Maps.Pushpin(center, { text: '1' });
        //map.entities.push(pin);

        $("#map").show();
        $("#closeMap").show('fast');
        $("body").css("overflow", "hidden");
    }

    function HideMap()
    {
        $("#closeMap").hide('fast');
        $("#map").hide();
        $("body").css("overflow", "auto");
        //map.entities.clear();
    }

    var infoBoxes = new Object();

    function GetMap()
    {
        var mapOptions = {
            credentials: '@System.Configuration.ConfigurationManager.AppSettings["bindMapsKey"]',
            mapTypeId: Microsoft.Maps.MapTypeId.road,
            center: new Microsoft.Maps.Location(@staticContent.RequestItems.MapCenter),
            zoom: 13,
            showScalebar: true
        }

        map = new Microsoft.Maps.Map(document.getElementById("map"), mapOptions);

        //var center = map.getCenter();

        //var pin = new Microsoft.Maps.Pushpin(center, { text: '1' });
        //map.entities.push(pin);

        infobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), { visible: false, offset: new Microsoft.Maps.Point(0, 20) });

        map.entities.push(infobox);

        for (var i = 0; i < requestItems.length; i++)
        {
            var item = requestItems[i];

            if (item.Geoposition && item.Geoposition != null && item.Geoposition.length > 0)
            {
                var latLongArray = (item.Geoposition).split(",");

                var latitude = parseFloat(latLongArray[0]);
                var longitude = parseFloat(latLongArray[1]);

                var supportersCount = GetSupporters(item.Id);

                supportersCount++;

                var pin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(latitude, longitude), { icon: '/content/images/pushpin1.png', width: 32, height: 66, text: supportersCount.toString() });
                pin.Title = item.Address;
                pin.Description = item.Description;
                pin.HtmlContent = "<img src='" + item.Thumbnail + "'/>";
                pin.RequestItemId = item.Id.toString();


                Microsoft.Maps.Events.addHandler(pin, 'mouseover', pinMouseHover);
                Microsoft.Maps.Events.addHandler(pin, 'mouseout', pinMouseHover);

                // Add handler for the pushpin click event.
                //Microsoft.Maps.Events.addHandler(pin, 'click', function () { displayInfobox(item.Id.toString()) });
                Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);

                // Hide the infobox when the map is moved.
                // Microsoft.Maps.Events.addHandler(map, 'viewchange', function () { hideInfobox(item.Id.toString()) });
                Microsoft.Maps.Events.addHandler(map, 'viewchange', hideInfobox);

                map.entities.push(pin);

                //infoBoxes[item.Id.toString()] = pinInfobox;
            }
        }

        /*
        // Create the locations
        var location1 = new Microsoft.Maps.Location(20, -20);
        var location2 = new Microsoft.Maps.Location(20, 20);
        var location3 = new Microsoft.Maps.Location(-20, 20);
        var location4 = new Microsoft.Maps.Location(-20, -20);

        // Create a polygon
        var vertices = new Array(location1, location2, location3, location4, location1);
        var polygoncolor = new Microsoft.Maps.Color(100, 100, 0, 100);
        var polygon = new Microsoft.Maps.Polygon(vertices, { fillColor: polygoncolor, strokeColor: polygoncolor });

        // Create the entity collection with the polygon and pushpins at each corner
        var polygonWithPins = new Microsoft.Maps.EntityCollection();
        polygonWithPins.push(polygon);
        polygonWithPins.push(new Microsoft.Maps.Pushpin(location1));
        polygonWithPins.push(new Microsoft.Maps.Pushpin(location2));
        polygonWithPins.push(new Microsoft.Maps.Pushpin(location3));
        polygonWithPins.push(new Microsoft.Maps.Pushpin(location4));

        // Add the shape to the map
        map.entities.push(polygonWithPins)*/

    }

    var infobox;

    function pinMouseHover(e)
    {
        var cursor = (e.eventName === 'mouseover') ? 'pointer'
            : 'url(http://ecn.dev.virtualearth.net/mapcontrol/v7.0/cursors/grab.cur), move';
        setMapCursor(cursor);
    }

    function setMapCursor(cursor)
    {
        $('.MicrosoftMap').css('cursor', cursor);
    }

    function displayInfobox(e)
    {
        if (e.targetType == 'pushpin')
        {
            ShowDetailsWindow(e.target.RequestItemId);
            //infobox.setLocation(e.target.getLocation());
            //infobox.setOptions({ visible: true, title: e.target.Title, description: e.target.Description, htmlContent: '<b>Custom HTML</b>' });
        }
    }


    //function displayInfobox(id)
    //{
    //    var infoBox = infoBoxes[id];
    //    infoBox.setOptions({ visible: true });
    //}

    function hideInfobox(id)
    {
        infobox.setOptions({ visible: false });

        return;
        var infoBox = infoBoxes[id];

        infoBox.setOptions({ visible: false });
    }

    $(document).ready(function () { GetMap(); });

    $(document).keyup(function (e)
    {

        if (e.keyCode == 27) { HideMap(); }   // esc
    });
</script>

@*<a href="javascript:ShowMap();" style="float:right;position:relative;margin-top:-40px;font-family:'Segoe UI Symbol';font-size:42px;">@Html.Raw(staticContent.RequestItems.MapSymbol)</a><br />*@
<a href="javascript:ShowMap();" style="float:right;position:relative;margin-top:-40px;font-size:20px;">@Html.Raw(staticContent.RequestItems.ShowOnMap) <span style="font-family:'Segoe UI Symbol';font-size:22px;">@Html.Raw(staticContent.RequestItems.MapSymbol)</span></a><br />

<ul class="thumbnails">
    @foreach (var item in Model.RequestItems)
    {
        try
        { 
        var itm = item;
        var req = itm.Request;
        var tit = req.Title;
        
        <li class="span4">
            <div class="thumbnail">
                <div style="text-align:center">
                    <h3>@Html.Raw(tit)</h3>
                </div>
                <img data-src="holder.js/260x180" src="@item.Thumbnail" style="width: 260px; height: 180px; cursor: pointer;"
                        onclick="SetDetails('@item.Id', '@item.Request.Title.Trim()', '@item.Photo.Replace(".jpg","_612.jpg")', '@item.Address.Trim()','@item.Geoposition', '@item.User.Name', '@item.CreationDate', '@item.Status', '@item.StatusInfo', '@item.Description.Trim()');">

                <div style="margin:10px">
                    <div style="float:right">
                        <span id="supporters_@item.Id">0</span>
                        <span style="font-family:'Segoe UI Symbol'">&nbsp;@Html.Raw(staticContent.RequestItems.SupportersSymbol)</span>
                    </div>
                    <script>
                        $(document).ready(function ()
                        {
                            GetStatus('@item.Id', '@item.Status');
                            SetSupporters('@item.Id');
                        });
                    </script>
                    @if (string.IsNullOrEmpty(item.Address))
                    {
                        <div>@staticContent.RequestItems.EmptyAddress</div>
                    }
                    else
                    {
                        <div>@item.Address</div>
                    }
                    <div>@item.CreationDate.ToString("dd/MM/yyyy HH:mm")</div>
                    <div id="status_@item.Id"></div>
                    <p><a href="/admin/deleterequestitem/@item.Id" onclick="return confirm('@string.Format(staticContent.Operations.DeleteMessage, item.Address)')" title="@staticContent.Operations.Delete" style="font-family:'Segoe UI Symbol';font-size:18px;">@Html.Raw(staticContent.Operations.DeleteSymbol)</a></p>
                </div>
            </div>
        </li>
    }catch{}
    }
</ul>

<div id="currentdetail" class="modal hide fade" style="z-index:10000">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="requestItemTitle">Title</h3>
    </div>
    <div id="detail_view" class="modal-body">
        <div style="display: inline">
            <div style="float: left;">
                <img id="requestItemPhotoFull" data-src="holder.js/360x270" alt="612x612" src="" style="width: 612px; height: 488px;">
            </div>
            <div style="float: left; margin-left: 15px; width: 367px;" >
                <div class="control-group" style="display:none;">
                    <strong>@staticContent.RequestItems.Id</strong>
                    <label id="requestItemId"></label>
                </div>

                <div class="control-group">
                    <strong>@staticContent.RequestItems.Address</strong>
                    <label id="requestItemAddress"></label>
                </div>

                <div class="control-group">
                    <strong>@staticContent.RequestItems.Geolocation</strong>
                    <label id="requestItemGeoposition"></label>
                </div>

                <div class="control-group">
                    <strong>@staticContent.RequestItems.CreatedBy</strong>
                    <label id="requestItemCreatedBy"></label>
                </div>

                <div class="control-group">
                    <strong>@staticContent.RequestItems.CreationDate</strong>
                    <label id="requestItemCreationDate"></label>
                </div>

                <div class="control-group">
                    <strong>@staticContent.RequestItems.Description</strong>
                    <p id="requestItemDescription">Value</p>
                </div>

                <div class="control-group">
                    <strong>@staticContent.RequestItems.Supporters<span style="font-family:'Segoe UI Symbol'">&nbsp;@Html.Raw(staticContent.RequestItems.SupportersSymbol)</span></strong>
                    <p id="requestItemSupporters">0</p>
                </div>

                <div class="control-group">
                    <strong>@staticContent.RequestItems.Status</strong>
                    <br />
                    <select id="Status" style="width:315px"></select>
                    <span id="statusCheck" style="font-family:'Segoe UI Symbol';color:green;">@Html.Raw(staticContent.Operations.OkSymbol)</span>
                    <span id="statusLoading">@staticContent.RequestItems.Saving</span>
                    <br />
                    <textarea id="statusInfo" rows="3" style="width:300px"></textarea>
                    <br />
                    <a id="singlebutton" class="btn btn-primary" href="javascript:SetStatus();">@staticContent.RequestItems.SaveStatus</a>
                </div>

            </div>
        </div>
    </div>
</div>

 <script type="text/javascript">
     var supporters = new Object();

     function SetSupporters(id)
     {
         $.getJSON("/api/requestitems/" + id + "/supporters/count", 
             function(data) 
             {
                 supporters[id] = data;
                 $("#supporters_" + id).text(data);
            });

     }

     function SetCitizen(id)
     {
         $.getJSON("/admin/GetCitizen/" + id,
             function (data)
             {
                 if (data != null)
                 {
                     $("#requestItemCreatedBy").text(data.Name);
                 }
             });

     }

     function GetSupporters(id)
     {
         if(supporters[id] == null)
         {
             return 0;
         }

         return supporters[id];
     }

     var allStatus = JSON.parse('@Html.Raw(jsonStatus)');

     function GetStatus(id, statusId)
     {
         var status = "";

         for (var i = 0; i < allStatus.length; i++)
         {
             if(allStatus[i].Value == statusId)
             {
                 status = allStatus[i].Text;
             }
         }

         $("#status_" + id).text(status);
     }

     function CreatedStatusDropDown(status)
     {
         HideStatusCheck();
         $("#Status").empty();

         for (var i = 0; i < allStatus.length; i++) {

            if (allStatus[i].Value == status) {
                $("#Status").append('<option  value="' + allStatus[i].Value + '" selected>' + allStatus[i].Text + '</option>');
            }
            else {
                $("#Status").append('<option value="' + allStatus[i].Value + '">' + allStatus[i].Text + '</option>');

            }
         }
     }

     function ShowDetails() {

         $("#currentdetail").modal({
             keyboard: false
         });
     }

     var currentId;
     function GetRequestItem(id)
     {
         for (var i = 0; i < requestItems.length; i++)
         {
             if(requestItems[i].Id == id)
             {
                 return requestItems[i];
             }
         }

         return null;
     }

     function ShowDetailsWindow(id)
     {
         var item = GetRequestItem(id);

         SetDetails(id, item.RequestTitle, item.Photo.replace(".jpg", "_612.jpg"), item.Address, item.Geoposition, item.UserName, item.CreationDate, item.Status, item.StatusInfo, item.Description)
     }

     function SetDetails(id, title, photo, address, geoposition, createdBy, creationDate, status, statusInfo, description)
     {
         currentId = id;

         //Clear
         $("#requestItemPhotoFull").empty();
         $("#requestItemTitle").empty();
         $("#requestItemId").empty();
         $("#requestItemAddress").empty();
         $("#requestItemGeoposition").empty();
         $("#requestItemCreatedBy").empty();
         $("#requestItemCreationDate").empty();
         $("#requestItemStatus").empty();
         $("#requestItemDescription").empty();
         $("#requestItemSupporters").empty();
         $("#statusInfo").empty();
            
         
         //Add
        $("#requestItemPhotoFull").attr("src", photo);
        $("#requestItemTitle").text(title);
        $("#requestItemId").text(id);
        $("#requestItemAddress").text(address);
        $("#requestItemGeoposition").text(geoposition);
        $("#requestItemCreatedBy").text(createdBy);
        $("#requestItemCreationDate").text(creationDate);
        $("#requestItemStatus").text(status);
        $("#requestItemDescription").text(description);
        $("#requestItemSupporters").text(GetSupporters(id));
        $("#statusInfo").val(statusInfo);

        CreatedStatusDropDown(status);
        ShowDetails();
     }

     function HideStatusCheck()
     {
         $("#statusLoading").hide();
         $("#statusCheck").hide();
     }

     function ShowStatusCheck()
     {
         $("#statusLoading").hide();
         $("#statusCheck").show();
     }

     function ShowStatusLoading()
     {
         $("#statusLoading").show();
         $("#statusCheck").hide();
     }

     function SetStatus()
     {
         ShowStatusLoading();

         var status = document.getElementById("Status").value;
         var statusInfo = $("#statusInfo").val();

         $.getJSON("/Admin/SetRequestItemStatus?id=" + currentId + "&status=" + status + "&statusInfo=" + statusInfo,
            function (data)
            {
                if (data == true)
                {
                    ShowStatusCheck();
                    GetStatus(currentId, status);
                    setTimeout(function () { location.reload() }, 1000);
                }
                else
                {
                    alert('@staticContent.RequestItems.SaveStatusErrorMessage');
                }
            },
            function ()
            {
                alert('@staticContent.RequestItems.SaveStatusErrorMessage');
            });
     }
 </script>
